import Konva from "konva";
import { BehaviorSubject, of } from "rxjs";
import { withLatestFrom } from "rxjs/operators";

export function useKonvaV1() {
  const stage$ = of(
    new Konva.Stage({
      container: "container",
      width: window.innerWidth,
      height: window.innerHeight,
    }),
  );

  const layer$ = of({
    textLayer: new Konva.Layer(),
    animLayer: new Konva.Layer(),
  });

  layer$
    .pipe(withLatestFrom(stage$))
    .subscribe(([{ textLayer, animLayer }, stage]) => {
      stage.add(textLayer).add(animLayer).batchDraw();
    });

  const shape$ = of({
    // Add static text
    text: new Konva.Text({
      x: 20,
      y: 20,
      text: "This text is in a static layer.\nThe circle below is in an animated layer.",
      fontSize: 16,
      fill: "black",
    }),
    // Add animated circle
    circle: new Konva.Circle({
      x: 100,
      y: 100,
      radius: 30,
      fill: "red",
    }),
  });
  // // effect
  // textLayer.add(text);

  // // effect
  // animLayer.add(circle);

  shape$
    .pipe(withLatestFrom(layer$))
    .subscribe(([{ text, circle }, { animLayer }]) => {
      animLayer.add(text).add(circle);
    });
  // Create animation
  const anim$ = new BehaviorSubject<
    (
      stage: Konva.Stage,
      animLayer: Konva.Layer,
      circle: Konva.Circle,
    ) => Konva.Animation
  >(
    (stage: Konva.Stage, animLayer: Konva.Layer, circle: Konva.Circle) =>
      new Konva.Animation((frame) => {
        // Move circle in a figure-8 pattern
        const scale = 100;
        const centerX = stage.width() / 2;
        const centerY = stage.height() / 2;

        circle.x(centerX + Math.sin(frame.time / 1000) * scale);
        circle.y(centerY + Math.sin(frame.time / 2000) * scale);
      }, animLayer),
  );

  // call effect
  anim$
    .pipe(withLatestFrom(stage$, layer$, shape$))
    .subscribe(([anim, stage, { animLayer }, { circle }]) =>
      anim(stage, animLayer, circle).start(),
    );
}
// stage
//  textLayer
//    text
//  animLayer
//    circle

// stage -> animLayer -> circle -> anim
